/**
 * @Author: jinye
 * @Date:   2016-02-24 15:19:59
 */

'use strict';
var fs      = require('fs');
var path    = require('path');
var gulp    = require('gulp');
var gutil   = require('gulp-util');
var argv    = require('minimist')(process.argv.slice(2));
var webpack = require('webpack');
var rimraf  = require('rimraf');
var proxy   = require('http-proxy-middleware');

var ROOT_PATH = process.cwd() + '/src';
var DIST_PATH = process.cwd() + '/dist';

var DEBUG = !!argv.debug;

var webpackConfig = require('./webpack.make')({debug: DEBUG});

function readHTMLFile() {
    var files = fs.readdirSync(DIST_PATH) || [];
    var temp  = []
    files.map(function(f){
        if (/html/.test(f)) {
            temp.push(path.join(DIST_PATH, f))
        }
    })
    return temp;
}

/*
 |--------------------------------------------------------------------------
 | HTTP Server 服务器
 |--------------------------------------------------------------------------
 */
gulp.task('browser-sync', function () {

    var browserSync = require('browser-sync').create();
    var compiler    = webpack(webpackConfig), bundleStart = null;

    var webpackDevMiddleware = require('webpack-dev-middleware')(compiler, {
        // IMPORTANT: dev middleware can't access config, so we should
        // provide publicPath by ourselves
        publicPath: webpackConfig.output.publicPath,
        // pretty colored output
        stats: {colors: true, chunks: false}
        // for other settings see
        // http://webpack.github.io/docs/webpack-dev-middleware.html
    })

    var webpackHotMiddleware = require('webpack-hot-middleware')(compiler);

    // 反向代理中间件用于跨域请求
    var proxyMiddleware = proxy('/ctg-mainframe-web',{
        target: "http://132.122.239.7:8098",
        // target: "http://localhost:8098",
        // target: "http://134.132.93.246:8098", // 刘延均
        changeOrigin: true
    })

    compiler.plugin('compile', function () {
        console.log('Bundling...');
        bundleStart = Date.now();
    });

    // We also give notice when it is done compiling, including the
    // time it took. Nice to have
    compiler.plugin('done', function () {
        console.log('Bundled in ' + (Date.now() - bundleStart) + 'ms!');
    });

// force page reload when html-webpack-plugin template changes
    compiler.plugin('compilation', function (compilation) {
        compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
            webpackHotMiddleware.publish({ action: 'reload' })
            cb()
        })
    })

    browserSync.init({
        server: {
            baseDir: './src',
            middleware: [webpackDevMiddleware, webpackHotMiddleware, proxyMiddleware],
            files: [
                ROOT_PATH + '*.html'
            ]
        },
        port: 8098,
        open : false
    })
})

gulp.task('js-hint', function() {
    var jshint  = require('gulp-jshint');
    var stylish = require('jshint-stylish');
    return gulp.src([
        ROOT_PATH + '/*.js', ROOT_PATH + '/views/**/*.js'
    ]).pipe(jshint()).pipe(jshint.reporter(stylish));
});

gulp.task('clean', ['js-hint'], function(cb) {
    rimraf(DIST_PATH,cb)
})

// webpack 打包任务
gulp.task("pack", ['clean'], function(callback) {
    webpack(webpackConfig, function(err, stats) {
        if(err) throw new gutil.PluginError("webpack", err);
        gutil.log('[webpack]', stats.toString({colors: true, profile: true, chunks: false}));
        callback();
    });
});


gulp.task('production', ['copy:js', 'copy:mock','path'], function() {
    /*var browserSync = require('browser-sync').create();
    browserSync.init({
        server: {
            baseDir: './dist'
        },
        browser: []
    })*/
});

gulp.task('copy:js',function(){
    return gulp.src(ROOT_PATH + '/assets/libs/**/*').pipe(gulp.dest(DIST_PATH + '/libs'))
});

gulp.task('copy:mock',function(){
    return gulp.src(ROOT_PATH + '/mocks/**/*').pipe(gulp.dest(DIST_PATH + '/mocks'))
});

gulp.task('path', function() {
    var replace = require('gulp-replace');
    var htmlFiles = readHTMLFile();
    return gulp.src(htmlFiles)
        .pipe(replace(/assets\//g, ''))
        .pipe(replace(/\.\.\//g, ''))
        .pipe(gulp.dest(DIST_PATH));
});

gulp.task("default", function(){
    var runSequence = require('run-sequence');
    if (DEBUG) return runSequence('browser-sync');
    runSequence('pack','production')
});